package com.example.demo.controller;

import com.example.demo.dto.QuestionDTO;
import com.example.demo.model.Question;
import com.example.demo.model.User;
import com.example.demo.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
//发布页面控制类
@Controller
public class PublishController {
    @Autowired
    private QuestionService questionService;

    @GetMapping("/publish/{id}")
    public String edit(@PathVariable(name="id") Integer id,
                       Model model){
        QuestionDTO question = questionService.getById(id);
        model.addAttribute("title",question.getTitle());
        model.addAttribute("description",question.getDescription());
        model.addAttribute("tag",question.getTag());
        model.addAttribute("id",question.getId());
        return "publish";
    }

    @GetMapping("/publish")
    public String publish(){
        return "publish";
    }
//    接收传入地址为publish的数据
    @PostMapping("/publish")
    public String doPublish(
//            将数据分发值相应位置
            @RequestParam(value = "title",required = false) String title,
            @RequestParam(value = "description",required = false) String description,
            @RequestParam(value = "tag",required = false) String tag,
            @RequestParam(value = "id",required = false) Integer id,
//            将数据存放modle中，方便回显至页面
            HttpServletRequest request,
            Model model) {
            model.addAttribute("title",title);
            model.addAttribute("description",description);
            model.addAttribute("tag",tag);
//一些空数据判断
            if(title == null || title==""){
                model.addAttribute("error", "标题不可为空");
                return "publish";
            }
            if(description == null || description==""){
                model.addAttribute("error", "描述不可为空");
                return "publish";
            }
            if(tag == null || tag==""){
                model.addAttribute("error", "标签不可为空");
                return "publish";
            }


//用户已登录？
        User user=(User)request.getSession().getAttribute("user");

        if(user==null) {
            model.addAttribute("error", "User未登录");
            return "publish";
        }
//用question保存“问题”数据
        Question question=new Question();
        question.setTitle(title);
        question.setDescription(description);
        question.setTag(tag);
        question.setCreator(user.getId());
        question.setId(id);
        questionService.createOrUpdate(question);
//        插入数据库
        return "redirect:/";
        }

}
